<template>
  <div class="p-4">
    <div style="display: flex; justify-content: space-between">
      <div style="width: 80%">
        <SiteAnalysis class="!my-4 enter-y" :loading="loading" />
      </div>
      <div style="width: 19%">
        <GrowCard :loading="loading" class="enter-y" />
      </div>
    </div>
    <div style="margin: 30px 0">
      <Collapse v-model:activeKey="activeKeyNodeList" accordion @change="onTabChange">
        <CollapsePanel :header="item.header" v-for="(item, index) in tabListTitle" :key="index">
          <Tree
            :tree-data="groupedData"
            :replaceFields="{ children: 'children', title: 'title', key: 'key' }"
            v-model:expandedKeys="expandedKeys"
          >
            <template #title="{ title, data }">
              <span v-html="title"></span>
              <Button
                v-if="!data.children"
                style="margin-left: 20px"
                @click="handleRestart(data)"
                size="small"
                :disabled="data.disabled"
                >重启
              </Button>
              <Button
                v-else
                style="margin-left: 20px"
                @click="handleRestartMvm(data)"
                size="small"
                :disabled="data.item.disabled"
                >重启 <span style="color: #999; font-size: 12px">(重启脚本)</span></Button
              >
            </template>
          </Tree>
        </CollapsePanel>
      </Collapse>
    </div>
    <div>
      <BasicTable @register="registerTable" />
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { Collapse, CollapsePanel, Tree, Button, message } from 'ant-design-vue';
  import { onMounted, ref, watch } from 'vue';
  import GrowCard from './components/GrowCard.vue';
  import SiteAnalysis from './components/SiteAnalysis.vue';
  import { BasicTable, useTable } from '@/components/Table';
  import {
    analysisGetNodeStatusAPI,
    getNodeLogs,
    analysisGetDataAPI,
    getEchartAPI,
    getNodeLogsOfflineAPI,
    getNodeDetailAPI,
    restartNodeAPI,
    allRestartNodeAPI,
  } from '@/api/demo/analysis';
  import { getlistAPI, dataDeleteAPI } from '@/api/demo/video';
  import { useECharts } from '@/hooks/web/useECharts';
  import { useI18n } from '@/hooks/web/useI18n';

  const expandedKeys = ref<string[]>([]);
  const loading = ref(true);
  const aliveNode = ref([]);
  const deadNode = ref([]);
  const activeKeyNode = ref([]);
  const { t } = useI18n();
  const activeKeyNodeList = ref([]);
  const thread = ref([]);
  const NodeList = ref({});
  const columns = ref([
    {
      title: t('sys.analysis.columns.platformId'),
      dataIndex: 'platformId',
      width: 80,
      customRender: ({ text }) => {
        const platformMap = {
          1: t('sys.analysis.Dianping'),
          2: t('sys.analysis.Douyin'),
        };
        return platformMap[text] || t('sys.analysis.Unknown');
      },
    },
    {
      title: t('sys.analysis.columns.type'),
      dataIndex: 'type',
      width: 80,
    },
    {
      title: t('sys.analysis.columns.target'),
      dataIndex: 'target',
      width: 80,
    },
    {
      title: t('sys.analysis.columns.mac'),
      dataIndex: 'mac',
      width: 80,
    },
    {
      title: t('sys.analysis.columns.node'),
      dataIndex: 'node',
      width: 80,
    },
    {
      title: t('sys.analysis.columns.status'),
      dataIndex: 'status',
      width: 80,
      customRender: ({ text }) => {
        return text == '-1' ? t('sys.analysis.offLine') : t('sys.analysis.onLine');
      },
    },
    {
      title: t('sys.analysis.columns.count'),
      dataIndex: 'count',
      width: 80,
    },
  ]);
  const columnsOffline = ref([
    {
      title: t('sys.analysis.columnsOffline.taskId'),
      dataIndex: 'id',
    },
    {
      title: t('sys.analysis.columnsOffline.mac'),
      dataIndex: 'mac',
    },
    {
      title: t('sys.analysis.columnsOffline.node'),
      dataIndex: 'node',
    },
    {
      title: t('sys.analysis.columnsOffline.type'),
      dataIndex: 'type',
    },
    {
      title: t('sys.analysis.columnsOffline.target'),
      dataIndex: 'target',
    },
    {
      title: t('sys.analysis.columnsOffline.offline'),
      dataIndex: 'offline',
    },
    {
      title: t('sys.analysis.columnsOffline.online'),
      dataIndex: 'online',
    },
  ]);
  const total = ref(0);
  const deadNodeCount = ref(0);
  const groupedData = ref([]);
  const dataSource = ref([]);

  setTimeout(() => {
    loading.value = false;
  }, 1500);

  const [registerTableModel, { updateTableData }] = useTable({
    dataSource: dataSource,
    rowKey: 'id',
    columns: columns,
    useSearchForm: false,
    showTableSetting: true,
    bordered: true,
    scroll: { y: 200 },
  });

  const [registerTable, { reload: refresh }] = useTable({
    title: t('sys.analysis.nodeOffLine'),
    api: async (params) => {
      const result = (await getNodeLogsOfflineAPI()) as { items: any[]; total: number };
      return result;
    },
    rowKey: 'id',
    columns: columnsOffline,
    useSearchForm: false,
    showTableSetting: true,
    bordered: true,
    scroll: { y: 200 },
  });

  async function getNodeStatus(data) {
    let Data = await getNodeLogs(data);
    groupedData.value = groupByMac(Data.data);
    dataSource.value = Data.data;
    total.value = Data.data.length || 0;

    const offlineNodes = Data.data.filter((node) => node.status === -1);
    deadNode.value = offlineNodes;

    const offlineCount = offlineNodes.length;
    deadNodeCount.value = offlineCount;

    const onlineNodes = Data.data.filter((node) => node.status === 1);
    const onlineCount = onlineNodes.length;

    const runningNodes = Data.data.filter((node) => node.status === 2);
    const runningCount = runningNodes.length;

    const unavailableNodes = Data.data.filter((node) => node.status === 0);
    const unavailableCount = unavailableNodes.length;

    updateHeaders(data, total.value, offlineCount, onlineCount, unavailableCount);
  }

  function groupByMac(data) {
    const groupedData = {};

    data.forEach((item) => {
      const { mac } = item;
      const { vmName } = item;

      if (!groupedData[mac]) {
        groupedData[mac] = {
          ...item,
          mac,
          vmName,
          children: [],
          offlineCount: 0,
          onlineCount: 0,
          runningCount: 0,
          unavailableCount: 0, // 添加不可用计数
          disabled: false, // 添加 disabled 属性
        };
      }
      groupedData[mac].children.push(item);
      if (item.status == '-1') {
        groupedData[mac].offlineCount++;
      } else if (item.status == '1') {
        groupedData[mac].onlineCount++;
      } else if (item.status == '2') {
        groupedData[mac].runningCount++;
      } else if (item.status == '0') {
        groupedData[mac].unavailableCount;
      }
    });

    return Object.values(groupedData).map((item) => ({
      title: `${item.vmName} (<span style="color: #52c41a">在线: ${item.onlineCount}</span>, <span style="color: #1890ff">运行: ${item.runningCount}</span>,  <span style="color: #ff4d4f">离线: ${item.offlineCount}</span>,<span style="color: #929292">不可用: ${item.unavailableCount}</span>)`,
      key: item.mac,
      item: item,
      disabled: item.disabled, // 传递 disabled 属性
      children: item.children.map((child) => ({
        ...child,
        title: `节点 : ${child.node} 状态 : <span style="color: ${child.status == '-1' ? '#ff4d4f' : child.status == '1' ? '#52c41a' : child.status == '2' ? '#1890ff' : '#ccc'}">${child.status == '-1' ? '离线' : child.status == '1' ? '在线' : child.status == '2' ? '运行' : child.status == '0' ? '不可用' : '重启中'}</span>`,
        key: child.node || child.id.toString(), // 确保 key 是唯一的
        disabled: false, // 添加 disabled 属性
      })),
    }));
  }

  const tabListTitle = ref([
    {
      key: 'mv_list',
      tab: '设备数量',
      header: '',
    },
    {
      key: 'mv_transfer',
      tab: '采集数据',
      header: '',
    },
  ]);

  const activeKey = ref('mv_list');

  function onTabChange(key) {
    activeKey.value = tabListTitle.value[key].key;
    getNodeStatus(activeKey.value);
  }

  async function change(key) {
    let Data = await getNodeDetailAPI(dataSource.value[key].id);
    thread.value = Data.data;
  }
  async function handleRestart(node) {
    const ids = [];
    if (node.children) {
      ids.push(...node.children.map((child) => child.id));
    } else {
      ids.push(node.id);
    }
    let Data = await restartNodeAPI(ids);
    if (Data.code == 200) {
      message.success(t('sys.analysis.restartSucces'));
      // 禁用重启按钮
      if (node.children) {
        node.children.forEach((child) => {
          child.disabled = true;
        });
      } else {
        node.disabled = true;
      }
      // 更新 groupedData
      groupedData.value = [...groupedData.value];
    }
  }

  async function handleRestartMvm(node) {
    let Data = await allRestartNodeAPI([node.item]);
    if (Data.code == 200) {
      message.success(t('sys.analysis.restartSucces'));
      // 禁用重启按钮
      node.item.disabled = true;
      // 更新 groupedData
      groupedData.value = [...groupedData.value];
    }
  }

  function updateHeaders(key, totalNodes, offlineCount, onlineCount, unavailableCount) {
    const headers = {
      mv_list: `${t('sys.devstatistics.deviceAllCount')} : \n\u00A0\u00A0\u00A0\u00A0\u00A0${t('sys.analysis.share')} ${totalNodes} ${t('sys.analysis.node')}\n\u00A0\u00A0\u00A0\u00A0\u00A0${t('sys.analysis.onLine')}: ${onlineCount}\n\u00A0\u00A0\u00A0\u00A0\u00A0${t('sys.analysis.offLine')}: ${offlineCount}\n\u00A0\u00A0\u00A0\u00A0\u00A0${t('sys.analysis.unusable')}: ${unavailableCount}`,
      mv_transfer: `${t('sys.analysis.everynum')} : \n\u00A0\u00A0\u00A0\u00A0\u00A0${t('sys.userlist.columns.taskprocess2')} ${totalNodes} \n\u00A0\u00A0\u00A0\u00A0\u00A0${t('sys.userlist.columns.taskprocess3')} ${totalNodes}\n\u00A0\u00A0\u00A0\u00A0\u00A0${t('sys.userlist.columns.taskprocess4')}: ${onlineCount}\n\u00A0\u00A0\u00A0\u00A0\u00A0${t('sys.userlist.columns.taskprocess5')}: ${offlineCount}`,
    };

    tabListTitle.value.forEach((item) => {
      if (item.key === key) {
        item.header = headers[item.key];
      }
    });
  }

  onMounted(() => {
    tabListTitle.value.forEach((item) => {
      getNodeStatus(item.key);
    });
  });
</script>

<style scoped>
  .tag-div {
    display: flex;
  }

  .tag-div > div {
    margin-right: 20px;
    padding: 2px 20px;
  }

  .tag-div > div > span {
    margin-left: 10px;
    font-weight: bold;
  }

  .coll-p > span {
    margin-right: 20px;
    color: red;
  }

  .title-p :deep(.ant-collapse-header-text) {
    line-height: 1.5; /* 增加行间距 */
    white-space: pre;
  }
</style>
`
